﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using System.Data;
using System.Text;
//using log4net;
using System.Reflection;

public partial class ShopTaskList : ExtBaseRpt
{
    mrjapp mrj = new mrjapp();
    string mid;
    protected void Page_Load(object sender, EventArgs e)
    {
        mid = Request.Params["mid"];
        if (!X.IsAjaxRequest)
        {
            try
            {
                InsActLog(mid, "浏览");
                txtBigAreaName.GetStore().DataSource = mydb.DM_GetDateSet("SELECT DISTINCT ProvinceName AS BigAreaName FROM t_task_shop_permissions "); //select distinct BigAreaName from V_ShopList
                txtAreaName.GetStore().DataSource = mydb.DM_GetDateSet("SELECT DISTINCT AreaName FROM t_task_shop_permissions "); //select distinct AreaName from V_ShopList
            }
            catch (Exception ex)
            {
                ShowBox("错误：" + ex.Message);
            }
        }
        if (Session["UserID"] == null)
        {
            ShowBox("用户登入超时请求重新登入");
        }
    }

    protected void StartDateField(object sender, DirectEventArgs e)
    {
        this.txtProcessingTimeEnd.MinDate = Convert.ToDateTime(this.txtProcessingTimeBegin.Text);
        int Begin = Convert.ToInt32(Convert.ToDateTime(this.txtProcessingTimeBegin.Text).DayOfWeek);
        if (Begin == 0)
        {
            this.txtProcessingTimeEnd.MaxDate = Convert.ToDateTime(this.txtProcessingTimeBegin.Text);
            this.txtProcessingTimeEnd.Text = this.txtProcessingTimeBegin.Text;
        }
        else
        {
            this.txtProcessingTimeEnd.MaxDate = Convert.ToDateTime(this.txtProcessingTimeBegin.Text).AddDays(7 - Begin);
            if (Convert.ToDateTime(this.txtProcessingTimeEnd.Text) < Convert.ToDateTime(this.txtProcessingTimeBegin.Text))
            {
                this.txtProcessingTimeEnd.Text = this.txtProcessingTimeBegin.Text;
            }
            else if (Convert.ToDateTime(this.txtProcessingTimeEnd.Text) > Convert.ToDateTime(this.txtProcessingTimeBegin.Text).AddDays(7 - Begin))
            {
                this.txtProcessingTimeEnd.Text = Convert.ToDateTime(this.txtProcessingTimeBegin.Text).AddDays(7 - Begin).ToString();
            }
        }

    }

    protected void BtnQureyUser(object sender, DirectEventArgs e)
    {
        try
        {
            string sql = string.Empty;
            string strBigAreaName = this.txtBigAreaName.Text;
            string strAreaName = this.txtAreaName.Text;
            string strShopName = this.txtShopName.Text.Trim();
            string strTaskType = this.cboTaskType.SelectedItem.Value;
            string txtProcessingTimeBegin = this.txtProcessingTimeBegin.Text;
            string txtProcessingTimeEnd = this.txtProcessingTimeEnd.Text;
            if (string.IsNullOrEmpty(txtProcessingTimeBegin) || Convert.ToDateTime(txtProcessingTimeBegin) == Convert.ToDateTime("0001-01-01 00:00:00"))
            {
                ShowBox("请输入开始日期条件！");
                return;
            }
            if (string.IsNullOrEmpty(txtProcessingTimeEnd) || Convert.ToDateTime(txtProcessingTimeEnd) == Convert.ToDateTime("0001-01-01 00:00:00"))
            {
                ShowBox("请输入结束日期条件！");
                return;
            }

            txtProcessingTimeBegin = Convert.ToDateTime(txtProcessingTimeBegin).ToString("yyyy-MM-dd");
            txtProcessingTimeEnd = Convert.ToDateTime(txtProcessingTimeEnd).ToString("yyyy-MM-dd");

            string strTab = string.Empty;

            #region 废弃
            ////-- (SELECT ShopID,ShopName,BigAreaName,AreaName FROM V_ShopList WHERE 1=1 AND BigAreaName='湖南省' AND AreaName='郴州市' AND (shopname LIKE '%郴州永%' OR ShopID=''))
            //strTab += " (SELECT ShopID,ShopName,BigAreaName,AreaName FROM V_ShopList WHERE 1=1 ";

            //if (!string.IsNullOrEmpty(strBigAreaName))
            //{
            //    strTab += " AND BigAreaName='" + strBigAreaName + "' ";
            //}
            //if (!string.IsNullOrEmpty(strAreaName))
            //{
            //    strTab += " AND AreaName='" + strAreaName + "' ";
            //}
            //if (!string.IsNullOrEmpty(strShopName))
            //{
            //    strTab += " AND (shopname LIKE '%" + strShopName + "%' OR ShopID='" + strShopName + "') ";
            //}
            //strTab += ") ";
            #endregion

            #region 新的权限控制过滤条件
            string UserName = Session["UserName"].ToString();
            string strPermissionsTab = string.Empty;
            bool IsAdmin = Convert.ToBoolean(Session["IsAdmin"].ToString());
            if (IsAdmin != true)
            {
                string CustomUserType = Session["CustomUserType"].ToString();
                if (CustomUserType != "1") //1:店铺任务管理员不需要通过零售分部过滤
                {
                    strPermissionsTab = string.Format(@" INNER JOIN
                    (
                	    SELECT DISTINCT OperatorAreaName FROM t_task_shop_permissions WHERE Display='{0}'
                    ) AS TSP2
                    ON TSP1.OperatorAreaName=TSP2.OperatorAreaName ", UserName);
                }
            }

            string strTSP1Where = string.Empty;
            if (!string.IsNullOrEmpty(strBigAreaName))
            {
                strTSP1Where += string.Format(@" AND TSP1.ProvinceName='{0}' ", strBigAreaName);
            }
            if (!string.IsNullOrEmpty(strAreaName))
            {
                strTSP1Where += string.Format(@" AND TSP1.AreaName='{0}' ", strAreaName);
            }

            string strAWhere = string.Empty;
            if (!string.IsNullOrEmpty(strShopName))
            {
                strAWhere += string.Format(@" AND (a.shopname LIKE '%{0}%' OR a.ShopID='{1}') ", strShopName, strShopName);
            }

            strTab = string.Format(@"SELECT DISTINCT a.ShopID,a.ShopName,a.BigAreaName,a.AreaName FROM V_ShopList AS a
INNER JOIN
(
	SELECT DISTINCT TSP1.ShopCode FROM t_task_shop_permissions AS TSP1
    {0}
	WHERE 1=1 AND TSP1.ShopState<>'已撤店'
    {1}
) AS b
ON a.shopcode=b.ShopCode
WHERE 1=1 {2} ", strPermissionsTab, strTSP1Where, strAWhere);

            #endregion


            sql += string.Format(@"SELECT 
	VSL.ShopName,
	TSL.ShopID,
	(VSL.BigAreaName+'/'+VSL.AreaName) AS ZoneAddress,
	TTS.TaskName,
	TDF.ProcessingDescribe,
	CONVERT(varchar(100), TDF.ProcessingTime, 120) AS ProcessingTime,
	TSL.TaskID,
    CASE WHEN IsNull(TDF.DetailID,0)=0 THEN 'custom_hide' ELSE convert(varchar(20),TDF.DetailID) END AS DetailID
FROM t_task_shoplist AS TSL
INNER JOIN ({0}) AS VSL
ON TSL.ShopID=VSL.ShopID
INNER JOIN t_task_set AS TTS
ON TTS.TaskID=TSL.TaskID 
 ", strTab);

            //LEFT JOIN t_task_detail_finish AS TDF
            //ON TDF.TaskID=TSL.TaskID";
            //sql += " AND TDF.ProcessingTime>='" + strProcessingTime + "' ";
            //sql += " AND TDF.ProcessingTime<='" + strProcessingTime + " 23:59:59" + "' ";

            sql += string.Format(@"LEFT JOIN 
(

		SELECT DISTINCT b.TaskID,USDR.ShopID,b.ProcessingDescribe,b.ProcessingTime,b.DetailID FROM [V_UserShopDataRights] AS USDR
		INNER JOIN 
		(
			SELECT DISTINCT b.TaskID,a.ProcessingCreator,a.ProcessingDescribe,a.ProcessingTime,a.DetailID FROM t_task_shoplist AS b
			INNER JOIN 
			(
				SELECT a.TaskID,a.ProcessingCreator,a.ProcessingDescribe,MAX(a.ProcessingTime) AS ProcessingTime,MAX(a.DetailID) AS DetailID FROM t_task_detail_finish AS a
				WHERE 1=1 
				AND a.ProcessingTime>='{0}'  
				AND a.ProcessingTime<='{1} 23:59:59'
				GROUP BY a.TaskID,a.ProcessingCreator,a.ProcessingDescribe
			) AS a ON a.TaskID=b.TaskID
		) AS b ON USDR.userid=b.ProcessingCreator

) AS TDF
ON TDF.ShopID=TSL.ShopID AND TDF.TaskID=TSL.TaskID", txtProcessingTimeBegin, txtProcessingTimeEnd);
            
            sql += " WHERE 1=1 ";
            
            //--AND TTS.TaskType=1
            if(!string.IsNullOrEmpty(strTaskType))
            {
                sql += "AND TTS.TaskType=" + strTaskType + " ";
            }

            //sql += " ORDER BY TDF.ProcessingTime DESC ";

            this.Store1.DataSource = mydb.DM_GetDateSet(sql);
            this.Store1.DataBind();
        }
        catch (Exception ex)
        {
            ShowBox("查询出错："+ex.Message);
        }
    }

    [DirectMethod(Namespace = "CompanyX")]
    public void TabPageChange(string JsonParams)
    {
        string txtProcessingTimeBegin = this.txtProcessingTimeBegin.Text;
        string txtProcessingTimeEnd = this.txtProcessingTimeEnd.Text;
        if (string.IsNullOrEmpty(txtProcessingTimeBegin) || Convert.ToDateTime(txtProcessingTimeBegin) == Convert.ToDateTime("0001-01-01 00:00:00"))
        {
            return;
        }
        else if (string.IsNullOrEmpty(txtProcessingTimeEnd) || Convert.ToDateTime(txtProcessingTimeEnd) == Convert.ToDateTime("0001-01-01 00:00:00"))
        {
            return;
        }
        else
        {
            BtnQureyUserView(null, null);
        }
    }

    protected void BtnQureyUserView(object sender, DirectEventArgs e)
    {
        try
        {
            string sql = string.Empty;
            string strBigAreaName = this.txtBigAreaName.Text;
            string strAreaName = this.txtAreaName.Text;
            string strShopName = this.txtShopName.Text.Trim();
            string strTaskType = this.cboTaskType.SelectedItem.Value;
            string txtProcessingTimeBegin = this.txtProcessingTimeBegin.Text;
            string txtProcessingTimeEnd = this.txtProcessingTimeEnd.Text;
            if (string.IsNullOrEmpty(txtProcessingTimeBegin) || Convert.ToDateTime(txtProcessingTimeBegin) == Convert.ToDateTime("0001-01-01 00:00:00"))
            {
                ShowBox("请输入开始日期条件！");
                return;
            }
            if (string.IsNullOrEmpty(txtProcessingTimeEnd) || Convert.ToDateTime(txtProcessingTimeEnd) == Convert.ToDateTime("0001-01-01 00:00:00"))
            {
                ShowBox("请输入结束日期条件！");
                return;
            }

            txtProcessingTimeBegin = Convert.ToDateTime(txtProcessingTimeBegin).ToString("yyyy-MM-dd");
            txtProcessingTimeEnd = Convert.ToDateTime(txtProcessingTimeEnd).ToString("yyyy-MM-dd");

            string strTab = string.Empty;

            #region 废弃
            ////-- (SELECT ShopID,ShopName,BigAreaName,AreaName FROM V_ShopList WHERE 1=1 AND BigAreaName='湖南省' AND AreaName='郴州市' AND (shopname LIKE '%郴州永%' OR ShopID=''))
            //strTab += " (SELECT ShopID,ShopName,BigAreaName,AreaName FROM V_ShopList WHERE 1=1 ";
            //if (!string.IsNullOrEmpty(strBigAreaName))
            //{
            //    strTab += " AND BigAreaName='" + strBigAreaName + "' ";
            //}
            //if (!string.IsNullOrEmpty(strAreaName))
            //{
            //    strTab += " AND AreaName='" + strAreaName + "' ";
            //}
            //if (!string.IsNullOrEmpty(strShopName))
            //{
            //    strTab += " AND (shopname LIKE '%" + strShopName + "%' OR ShopID='" + strShopName + "') ";
            //}
            //strTab += ") ";
            #endregion

            #region 新的权限控制过滤条件
            string UserName = Session["UserName"].ToString();
            string strPermissionsTab = string.Empty;
            bool IsAdmin = Convert.ToBoolean(Session["IsAdmin"].ToString());
            if (IsAdmin != true)
            {
                string CustomUserType = Session["CustomUserType"].ToString();
                if (CustomUserType != "1") //1:店铺任务管理员不需要通过零售分部过滤
                {
                    strPermissionsTab = string.Format(@" INNER JOIN
                    (
                	    SELECT DISTINCT OperatorAreaName FROM t_task_shop_permissions WHERE Display='{0}'
                    ) AS TSP2
                    ON TSP1.OperatorAreaName=TSP2.OperatorAreaName ", UserName);
                }
            }

            string strTSP1Where = string.Empty;
            if (!string.IsNullOrEmpty(strBigAreaName))
            {
                strTSP1Where += string.Format(@" AND TSP1.ProvinceName='{0}' ", strBigAreaName);
            }
            if (!string.IsNullOrEmpty(strAreaName))
            {
                strTSP1Where += string.Format(@" AND TSP1.AreaName='{0}' ", strAreaName);
            }

            string strAWhere = string.Empty;
            if (!string.IsNullOrEmpty(strShopName))
            {
                strAWhere += string.Format(@" AND (a.shopname LIKE '%{0}%' OR a.ShopID='{1}') ", strShopName, strShopName);
            }

            strTab = string.Format(@"SELECT DISTINCT a.ShopID,a.ShopName,a.BigAreaName,a.AreaName FROM V_ShopList AS a
INNER JOIN
(
	SELECT DISTINCT TSP1.ShopCode FROM t_task_shop_permissions AS TSP1
    {0}
	WHERE 1=1 AND TSP1.ShopState<>'已撤店'
    {1}
) AS b
ON a.shopcode=b.ShopCode
WHERE 1=1 {2} ", strPermissionsTab, strTSP1Where, strAWhere);

            #endregion

            sql += string.Format(@"SELECT 
	VSL.ShopName,
	TSL.ShopID,
	(VSL.BigAreaName+'/'+VSL.AreaName) AS ZoneAddress,
	TTS.TaskName,
	TDF.ProcessingDescribe,
	TDF.ProcessingTime,
	TSL.TaskID,
    CASE WHEN IsNull(TDF.DetailID,0)=0 THEN 'custom_hide' ELSE convert(varchar(20),TDF.DetailID) END AS DetailID,
    CASE WHEN IsNull(TDI.Url,'')='' THEN '../images/nopic.png' ELSE 'http://kmer-online-pic.oss-cn-shenzhen.aliyuncs.com/' + TDI.Url END AS Url,
	CASE WHEN ISNULL(TFB.DetailID,'')='' THEN 0 ELSE 1 END AS IsInsert,
	CASE WHEN ISNULL(TFB.IsRead,'')='' THEN 0 ELSE TFB.IsRead END AS IsRead  
FROM t_task_shoplist AS TSL
INNER JOIN ({0}) AS VSL
ON TSL.ShopID=VSL.ShopID
INNER JOIN t_task_set AS TTS
ON TTS.TaskID=TSL.TaskID 
 ", strTab);

            //LEFT JOIN t_task_detail_finish AS TDF
            //ON TDF.TaskID=TSL.TaskID";
            //sql += " AND TDF.ProcessingTime>='" + strProcessingTime + "' ";
            //sql += " AND TDF.ProcessingTime<='" + strProcessingTime + " 23:59:59" + "' ";

            sql += string.Format(@"INNER JOIN 
(

		SELECT DISTINCT b.TaskID,USDR.ShopID,b.ProcessingDescribe,b.ProcessingTime,b.DetailID FROM [V_UserShopDataRights] AS USDR
		INNER JOIN 
		(
			SELECT DISTINCT b.TaskID,a.ProcessingCreator,a.ProcessingDescribe,a.ProcessingTime,a.DetailID FROM t_task_shoplist AS b
			INNER JOIN 
			(
				SELECT a.TaskID,a.ProcessingCreator,a.ProcessingDescribe,MAX(a.ProcessingTime) AS ProcessingTime,MAX(a.DetailID) AS DetailID FROM t_task_detail_finish AS a
				WHERE 1=1 
				AND a.ProcessingTime>='{0}'
				AND a.ProcessingTime<='{1} 23:59:59'
				GROUP BY a.TaskID,a.ProcessingCreator,a.ProcessingDescribe
			) AS a ON a.TaskID=b.TaskID
		) AS b ON USDR.userid=b.ProcessingCreator

) AS TDF
ON TDF.ShopID=TSL.ShopID AND TDF.TaskID=TSL.TaskID
LEFT JOIN 
(
	SELECT a.DetailID,d.Url FROM t_task_detail_imglist AS a
	INNER JOIN 
	(
		--SELECT MAX(DID) AS DID,DetailID FROM t_task_detail_imglist GROUP BY DetailID

		SELECT MAX(dil.DID) AS DID,dil.DetailID FROM t_task_detail_imglist AS dil
		INNER JOIN t_task_detail_finish AS a ON dil.DetailID=a.DetailID
		WHERE 1=1 
		AND a.ProcessingTime>='{0}'
		AND a.ProcessingTime<='{1} 23:59:59'
		GROUP BY dil.DetailID

	) AS b
	ON a.DID=b.DID
	INNER JOIN kmImages AS d
	ON d.ID=a.ImgID
) AS TDI 
ON TDI.DetailID=TDF.DetailID 
LEFT JOIN t_task_feedback AS TFB
ON TFB.DetailID=TDF.DetailID ", txtProcessingTimeBegin, txtProcessingTimeEnd);

            sql += " WHERE 1=1 ";

            //--AND TTS.TaskType=1
            if (!string.IsNullOrEmpty(strTaskType))
            {
                sql += "AND TTS.TaskType=" + strTaskType + " ";
            }

            //sql += " ORDER BY TDF.ProcessingTime DESC ";

            this.Store3.DataSource = mydb.DM_GetDateSet(sql);
            this.Store3.DataBind();
        }
        catch (Exception ex)
        {
            ShowBox("查询出错：" + ex.Message);
        }
    }

    protected void GetArea(object sender, DirectEventArgs e)
    {
        //select distinct AreaName from V_ShopList where BigAreaName =
        txtAreaName.GetStore().DataSource = mydb.DM_GetDateSet("SELECT DISTINCT AreaName FROM t_task_shop_permissions WHERE ProvinceName='" + txtBigAreaName.Value + "'");
        this.Store_AreaName.DataBind();
    }


    protected void RefreshDataSet(object sender, StoreReadDataEventArgs e)
    {
        BtnQureyUser(null, null);
    }

    protected void RefreshDataSetView(object sender, StoreReadDataEventArgs e)
    {
        BtnQureyUserView(null, null);
    }
    
    //保存任务反馈信息
    [DirectMethod(Namespace = "CompanyX")]
    public int TaskFeedbackSave(string JsonParams)
    {
        int intNum = 0;
        try
        {
            if (Session["UserID"] != null)
            {
                //反序列化为ShopImg对象 
                var model = JSON.Deserialize<SaveFeedbackRequestModel>(JsonParams);
                bool IsInsert = model.IsInsert;
                string DetailID = model.DetailID;
                string ShopID = model.ShopID;
                
                if (IsShop(DetailID, ShopID) == true)
                {
                    string UserID = Session["UserID"].ToString();
                    string FeedBackDescribe = this.txtFeedBackDescribe.Text.Trim();
                    if (FeedBackDescribe != "")
                    {
                        string TaskFinishLevel = model.TaskFinishLevel;
                        if (IsInsert == true)
                        {
                            string insertSql = string.Empty;
                            insertSql = string.Format(@"INSERT INTO [dbo].[t_task_feedback]([DetailID],[FeedBackCreator],[FeedBackDate],[FeedBackDescribe],[TaskFinishLevel]) 
                                                VALUES({0},{1},GETDATE(),'{2}','{3}')", DetailID, UserID, FeedBackDescribe, TaskFinishLevel);
                            intNum = mydb.DM_ExecuteNonQuery(insertSql);
                        }
                        else
                        {
                            string updateSql = string.Empty;
                            updateSql = string.Format(@"UPDATE [dbo].[t_task_feedback] SET [FeedBackCreator]={0},[FeedBackDate]=GETDATE(),[FeedBackDescribe]='{1}',[TaskFinishLevel]='{2}' 
                                                WHERE DetailID={3} ", UserID, FeedBackDescribe, TaskFinishLevel, DetailID);
                            intNum = mydb.DM_ExecuteNonQuery(updateSql);
                        }

                        if (intNum > 0)
                        {
                            string deleteSql = string.Format(@"DELETE FROM t_task_problem_imglist WHERE DetailID={0}", DetailID);
                            intNum = mydb.DM_ExecuteNonQuery(deleteSql);
                            if (intNum >= 0)
                            {
                                string[] ImgIDlist = model.ImgIDlist;
                                string[] sqlList = new string[ImgIDlist.Length];
                                for (int i = 0; i < ImgIDlist.Length; i++)
                                {
                                    string insertSql = string.Format(@"INSERT INTO t_task_problem_imglist([DetailID],[ImgID])VALUES({0},'{1}') ", DetailID, ImgIDlist[i]);
                                    sqlList[i] = insertSql;
                                }

                                bool isbol = mydb.ExecuteNonQueryTran(sqlList);
                                if (isbol == true)
                                {
                                    intNum = 1;
                                }
                                else
                                {
                                    intNum = -3;
                                }
                            }
                        }
                    }
                    else
                    {
                        intNum = -4;
                    }
                }
                else
                {
                    intNum = -2;
                }

            }
            else
            {
                ShowBox("错误：登入超时");
            }
        }
        catch(Exception ex)
        {
            ShowBox("错误：" + ex.Message);
        }
        return intNum;
    }

    //批处理反馈信息  
    [DirectMethod(Namespace = "CompanyX")]
    public int TaskBatchFeedbackSave(string JsonParams)
    {
        int intNum = 1;
        try
        {
            if (Session["UserID"] != null)
            {
                //反序列化为ShopImg对象
                var model = JSON.Deserialize<SaveBatchFeedbackRequestModel>(JsonParams);
                string TaskFinishLevel = model.TaskFinishLevel;
                string FeedBackDescribe = this.txtFeedBackDescribe1.Text.Trim();
                if (FeedBackDescribe != "")
                {
                    string UserID = Session["UserID"].ToString();
                    List<BatchFeedback_Model> BatchList = model.BatchList;
                    for (int i = 0; i < BatchList.Count; i++)
                    {
                        if (IsShop(BatchList[i].DetailID, BatchList[i].ShopID) == true)
                        {
                            if (BatchList[i].IsInsert == 0)
                            {

                                string insertSql = string.Empty;
                                insertSql = string.Format(@"INSERT INTO [dbo].[t_task_feedback]([DetailID],[FeedBackCreator],[FeedBackDate],[FeedBackDescribe],[TaskFinishLevel]) 
                                                VALUES({0},{1},GETDATE(),'{2}','{3}')", BatchList[i].DetailID, UserID, FeedBackDescribe, TaskFinishLevel);
                                intNum = mydb.DM_ExecuteNonQuery(insertSql);

                                //添加是修改已读
                                string sqlUpIsRead = string.Format(@"UPDATE t_task_detail_finish SET IsRead=1 WHERE 1=1 AND DetailID={0}", BatchList[i].DetailID);
                                mydb.DM_ExecuteNonQuery(sqlUpIsRead);
                            }
                            else if (BatchList[i].IsInsert == 1 && (BatchList[i].IsRead == 0))
                            {
                                string updateSql = string.Empty;
                                updateSql = string.Format(@"UPDATE [dbo].[t_task_feedback] SET [FeedBackCreator]={0},[FeedBackDate]=GETDATE(),[FeedBackDescribe]='{1}',[TaskFinishLevel]='{2}' 
                                                WHERE DetailID={3} ", UserID, FeedBackDescribe, TaskFinishLevel, BatchList[i].DetailID);
                                intNum = mydb.DM_ExecuteNonQuery(updateSql);
                            }
                        }
                    }

                    //重新加载视图列表数据 
                    BtnQureyUserView(null, null);
                }
                else
                {
                    intNum = -4;
                }
            }
            else
            {
                ShowBox("错误：登入超时");
            }
        }
        catch (Exception ex)
        {
            ShowBox("错误：" + ex.Message);
        }
        return intNum;
    }

    //查询任务完成详情信息
    [DirectMethod(Namespace = "CompanyX")]
    public TaskDetailResponseModel SelectTaskDetail(string JsonParams)
    {
        TaskDetailResponseModel resTaskDetail = new TaskDetailResponseModel();
        try
        {
            resTaskDetail.state = 0;
            //反序列化为ShopImg对象
            var model = JSON.Deserialize<TaskDetailRequestModel>(JsonParams);
            string strTaskID = model.TaskID;
            string DetailID = model.DetailID;
            string ShopID = model.ShopID;
            
            string SqlTaskSet = string.Empty;
            SqlTaskSet = string.Format(@"SELECT  
	TTS.TaskName,
	TTS.TaskType,
	TTS.ExecWeek,
	TTS.IsEnabled,
	TTS.TaskDescribe
FROM t_task_set AS TTS
WHERE 1=1
AND TTS.TaskID={0}", strTaskID);

            DataSet ds1 = mydb.DM_GetDateSet(SqlTaskSet);
            if (ds1 != null && ds1.Tables[0].Rows.Count > 0)
            {
                ModelHandler<Task_set_Model> modTaskSet = new ModelHandler<Task_set_Model>();
                resTaskDetail.task_set = modTaskSet.FillModel(ds1);
            }

            string SqlProblem = string.Format(@"SELECT ImgID FROM t_task_problem_imglist WHERE DetailID={0} ", DetailID);
            DataSet ProImg = mydb.DM_GetDateSet(SqlProblem);
            if (ProImg != null && ProImg.Tables[0].Rows.Count > 0)
            {
                ModelHandler<Task_Problem_Img_Model> modTaskSet = new ModelHandler<Task_Problem_Img_Model>();
                resTaskDetail.Problem = modTaskSet.FillModel(ProImg);
            }



            string SqlTaskFinish = string.Empty;
            SqlTaskFinish = string.Format(@"SELECT 
	TDF.ProcessingTime,
	TDF.ProcessingDescribe,
	TDF.IsRead,
	TDI.ImgID,
	IMG.Title,
    CASE WHEN IsNull(IMG.Url,'')='' THEN '../images/nopic.png' ELSE 'http://kmer-online-pic.oss-cn-shenzhen.aliyuncs.com/' + IMG.Url END AS Url,
	ROW_NUMBER()OVER(ORDER BY TDI.DID DESC)-1 AS RowIndex,
	CASE WHEN ROW_NUMBER()OVER(ORDER BY TDI.DID DESC)=1 THEN 'active' ELSE '' END AS Active
FROM t_task_detail_finish AS TDF
INNER JOIN t_task_detail_imglist AS TDI
ON TDI.DetailID=TDF.DetailID
LEFT JOIN dbo.kmImages AS IMG
ON IMG.ID=TDI.ImgID
WHERE 1=1 
AND TDF.DetailID={0}", DetailID);

            DataSet ds2 = mydb.DM_GetDateSet(SqlTaskFinish);
            if (ds2 != null && ds2.Tables[0].Rows.Count > 0)
            {
                resTaskDetail.ProcessingTime = ds2.Tables[0].Rows[0]["ProcessingTime"].ToString();
                resTaskDetail.ProcessingDescribe = ds2.Tables[0].Rows[0]["ProcessingDescribe"].ToString();
                bool bolIsRead = Convert.ToBoolean(ds2.Tables[0].Rows[0]["IsRead"]);
                if (bolIsRead == false && IsShop(DetailID, ShopID) == true)
                {
                    string sqlUpIsRead = string.Format(@"UPDATE t_task_detail_finish SET IsRead=1 WHERE 1=1 AND DetailID={0}", DetailID);
                    mydb.DM_ExecuteNonQuery(sqlUpIsRead);
                }

                this.Store2.DataSource = ds2;
                this.Store2.DataBind();

                this.Store4.DataSource = ds2;
                this.Store4.DataBind();
            }
            
            string SqlTaskFeedback = string.Empty;
            SqlTaskFeedback = string.Format(@"SELECT 
	TFB.DetailID,
	TFB.IsRead,
	TFB.TaskFinishLevel,
	TFB.FeedBackDescribe
FROM dbo.t_task_feedback AS TFB
WHERE 1=1 
AND TFB.DetailID={0}", DetailID);

            DataSet ds3 = mydb.DM_GetDateSet(SqlTaskFeedback);
            if (ds3 != null && ds3.Tables[0].Rows.Count > 0)
            {
                ModelHandler<Task_feedback_Model> modTaskFeedback = new ModelHandler<Task_feedback_Model>();
                resTaskDetail.task_feedback = modTaskFeedback.FillModel(ds3);
                this.txtFeedBackDescribe.Text = resTaskDetail.task_feedback[0].FeedBackDescribe;
                if (resTaskDetail.task_feedback[0].IsRead == true)
                {
                    this.txtFeedBackDescribe.ReadOnly = true;
                    this.btnTaskDetailSave.Disabled = true;
                }
                else
                {
                    this.txtFeedBackDescribe.ReadOnly = false;
                    this.btnTaskDetailSave.Disabled = false;
                }
            }
            else
            {
                this.txtFeedBackDescribe.ReadOnly = false;
                this.btnTaskDetailSave.Disabled = false;
                this.txtFeedBackDescribe.Text = "";
            }
            
            return resTaskDetail;
        }
        catch (Exception ex)
        {
            resTaskDetail.state = -1;
            resTaskDetail.error = ex.Message;
            return resTaskDetail;
        }
    }

    /// <summary>
    /// 判断陈列师是否有这家店铺的权限
    /// 时间：2018-04-11
    /// 作者：曹亚亮
    /// </summary>
    /// <param name="DetailID">任务详情ID</param>
    /// <param name="ShopID">店铺编码ID</param>
    /// <returns>true:存在 false:不存在</returns>
    public bool IsShop(string DetailID, string ShopID)
    {
        if (Session["UserName"] == null)
        {
            return false;
        }

        string UserName = Session["UserName"].ToString();
        string strSql = string.Format(@"SELECT COUNT(1) FROM t_task_detail_finish AS df 
INNER JOIN t_task_shoplist AS sl ON sl.TaskID=df.TaskID
INNER JOIN V_Shop AS vs ON vs.ShopID=sl.ShopID
INNER JOIN t_task_shop_permissions AS sp ON sp.ShopCode=vs.ShopCode 
WHERE 1=1
AND df.DetailID={0}
AND sp.Display='{1}'
AND vs.ShopID='{2}'", DetailID, UserName, ShopID);

        int Num = mydb.DM_GetExecuteScalar(strSql);
        if (Num > 0)
        {
            return true;
        }
        return false;
    }

    /// <summary>
    /// 接收查看任务详情请求参数
    /// </summary>
    public class TaskDetailRequestModel
    {
        /// <summary>
        /// 任务ID
        /// </summary>
        public string TaskID { get; set; }
        /// <summary>
        /// 处理详情ID
        /// </summary>
        public string DetailID { get; set; }
        /// <summary>
        /// 店铺代码
        /// </summary>
        public string ShopID { get; set; }
    }
    /// <summary>
    /// 响应任务完成详情实体类
    /// </summary>
    public class TaskDetailResponseModel
    {
        /// <summary>
        /// 响应状态
        /// </summary>
        public int state { get; set; }
        /// <summary>
        /// 任务设置详情
        /// </summary>
        public List<Task_set_Model> task_set { get; set; }
        /// <summary>
        /// 任务完成时间
        /// </summary>
        public string ProcessingTime { get; set; }
        /// <summary>
        /// 任务完成备注
        /// </summary>
        public string ProcessingDescribe { get; set; }
        /// <summary>
        /// 任务反馈详情
        /// </summary>
        public List<Task_feedback_Model> task_feedback { get; set; }
        /// <summary>
        /// 错误信息
        /// </summary>
        public string error { get; set; }
        /// <summary>
        /// 任务问题图片ID集合
        /// </summary>
        public List<Task_Problem_Img_Model> Problem { get; set; }
    }

    /// <summary>
    /// 任务设置明细实体类
    /// </summary>
    public class Task_set_Model
    {
        /// <summary>
        /// 任务名称
        /// </summary>
        public string TaskName { get; set; }
        /// <summary>
        /// 任务类型
        /// </summary>
        public int TaskType { get; set; }
        /// <summary>
        /// 执行时间
        /// </summary>
        public int ExecWeek { get; set; }
        /// <summary>
        /// 是否启用
        /// </summary>
        public bool IsEnabled { get; set; }
        /// <summary>
        /// 任务描述
        /// </summary>
        public string TaskDescribe { get; set; }
    }

    /// <summary>
    /// 任务问题图片实体类
    /// </summary>
    public class Task_Problem_Img_Model
    {
        /// <summary>
        /// 问题图片ID
        /// </summary>
        public Guid ImgID { get; set; }
    }

    /// <summary>
    /// 反馈信息实体类
    /// </summary>
    public class Task_feedback_Model {
        /// <summary>
        /// 任务完成ID
        /// </summary>
        public int DetailID { get; set; }
        /// <summary>
        /// 反馈信息是否已读
        /// </summary>
        public bool IsRead { get; set; }
        /// <summary>
        /// 反馈描述
        /// </summary>
        public string FeedBackDescribe { get; set; }
        /// <summary>
        /// 星评等级
        /// </summary>
        public string TaskFinishLevel { get; set; }
    }

    /// <summary>
    /// 保存反馈请求实体类
    /// </summary>
    public class SaveFeedbackRequestModel
    {
        /// <summary>
        /// true 添加 false 修改
        /// </summary>
        public bool IsInsert { get; set; }
        /// <summary>
        /// 任务完成ID
        /// </summary>
        public string DetailID { get; set; }
        /// <summary>
        /// 星评等级
        /// </summary>
        public string TaskFinishLevel { get; set; }
        /// <summary>
        /// 店铺编码ID
        /// </summary>
        public string ShopID { get; set; }
        /// <summary>
        /// 选择的问题图片ID数组
        /// </summary>
        public string[] ImgIDlist { get; set; }
    }

    /// <summary>
    /// 保存批处理反馈请求实体类
    /// </summary>
    public class SaveBatchFeedbackRequestModel {
        /// <summary>
        /// 星评等级
        /// </summary>
        public string TaskFinishLevel { get; set; }
        public List<BatchFeedback_Model> BatchList { get; set; }
    }
    /// <summary>
    /// 批处理反馈数据实体类
    /// </summary>
    public class BatchFeedback_Model {
        /// <summary>
        /// 任务处理详情ID
        /// </summary>
        public string DetailID { get; set; }
        /// <summary>
        /// 是否已提交反馈 1：是 0：否
        /// </summary>
        public int IsInsert { get; set; }
        /// <summary>
        /// 反馈意见是否已读 1：是 0：否
        /// </summary>
        public int IsRead { get; set; }
        /// <summary>
        /// 店铺代码
        /// </summary>
        public string ShopID { get; set; }
    }



    /// <summary>
    /// DataTable与实体类互相转换
    /// </summary>
    /// <typeparam name="T">实体类</typeparam>
    public class ModelHandler<T> where T : new()
    {
        #region DataTable转换成实体类

        /// <summary>
        /// 填充对象列表：用DataSet的第一个表填充实体类
        /// </summary>
        /// <param name="ds">DataSet</param>
        /// <returns></returns>
        public List<T> FillModel(DataSet ds)
        {
            if (ds == null || ds.Tables[0] == null || ds.Tables[0].Rows.Count == 0)
            {
                return null;
            }
            else
            {
                return FillModel(ds.Tables[0]);
            }
        }

        /// <summary>  
        /// 填充对象列表：用DataSet的第index个表填充实体类
        /// </summary>  
        public List<T> FillModel(DataSet ds, int index)
        {
            if (ds == null || ds.Tables.Count <= index || ds.Tables[index].Rows.Count == 0)
            {
                return null;
            }
            else
            {
                return FillModel(ds.Tables[index]);
            }
        }

        /// <summary>  
        /// 填充对象列表：用DataTable填充实体类
        /// </summary>  
        public List<T> FillModel(DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return null;
            }
            List<T> modelList = new List<T>();
            foreach (DataRow dr in dt.Rows)
            {
                //T model = (T)Activator.CreateInstance(typeof(T));  
                T model = new T();
                for (int i = 0; i < dr.Table.Columns.Count; i++)
                {
                    PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
                    if (propertyInfo != null && dr[i] != DBNull.Value)
                        propertyInfo.SetValue(model, dr[i], null);
                }

                modelList.Add(model);
            }
            return modelList;
        }

        /// <summary>  
        /// 填充对象：用DataRow填充实体类
        /// </summary>  
        public T FillModel(DataRow dr)
        {
            if (dr == null)
            {
                return default(T);
            }

            //T model = (T)Activator.CreateInstance(typeof(T));  
            T model = new T();

            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
                if (propertyInfo != null && dr[i] != DBNull.Value)
                    propertyInfo.SetValue(model, dr[i], null);
            }
            return model;
        }

        #endregion

        #region 实体类转换成DataTable

        /// <summary>
        /// 实体类转换成DataSet
        /// </summary>
        /// <param name="modelList">实体类列表</param>
        /// <returns></returns>
        public DataSet FillDataSet(List<T> modelList)
        {
            if (modelList == null || modelList.Count == 0)
            {
                return null;
            }
            else
            {
                DataSet ds = new DataSet();
                ds.Tables.Add(FillDataTable(modelList));
                return ds;
            }
        }

        /// <summary>
        /// 实体类转换成DataTable
        /// </summary>
        /// <param name="modelList">实体类列表</param>
        /// <returns></returns>
        public DataTable FillDataTable(List<T> modelList)
        {
            if (modelList == null || modelList.Count == 0)
            {
                return null;
            }
            DataTable dt = CreateData(modelList[0]);

            foreach (T model in modelList)
            {
                DataRow dataRow = dt.NewRow();
                foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
                {
                    dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null);
                }
                dt.Rows.Add(dataRow);
            }
            return dt;
        }

        /// <summary>
        /// 根据实体类得到表结构
        /// </summary>
        /// <param name="model">实体类</param>
        /// <returns></returns>
        private DataTable CreateData(T model)
        {
            DataTable dataTable = new DataTable(typeof(T).Name);
            foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
            {
                dataTable.Columns.Add(new DataColumn(propertyInfo.Name, propertyInfo.PropertyType));
            }
            return dataTable;
        }

        #endregion
    }
}

